import 'package:date_time_format/date_time_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_todolist/db/table/task_table.dart';
import 'package:flutter_todolist/pages/home/task_controller.dart';
import 'package:flutter_todolist/pages/home/task_type_controller.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';

import '../../util.dart';
import '../add_task/add_task_dialog.dart';

class TaskTimeLine extends StatefulWidget {
  const TaskTimeLine({Key? key}) : super(key: key);

  @override
  State<TaskTimeLine> createState() => _TaskTimeLineState();
}

class _TaskTimeLineState extends State<TaskTimeLine> with AutomaticKeepAliveClientMixin {

  TaskController taskCtrl = Get.find<TaskController>();
  TaskTypeController taskTypeCtrl = Get.find<TaskTypeController>();

  @override
  Widget build(BuildContext context) {
    return Obx(() => taskCtrl.taskList.isEmpty
      ? noTodo()
      : CustomScrollView(
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.symmetric(vertical: 15),
          sliver: SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
              bool showTimeStamp = false;
              if (index == 0) {
                showTimeStamp = true;
              } else {
                DateTime now = DateTime.fromMillisecondsSinceEpoch(taskCtrl.taskList[index].expiresTime!);
                DateTime before = DateTime.fromMillisecondsSinceEpoch(taskCtrl.taskList[index - 1].expiresTime!);
                // Duration difference = now.difference(before);
                // debugPrint('difference: $difference');
                // debugPrint('difference day: ${difference.inDays}');
                // debugPrint('now day: ${now.day}');
                // debugPrint('before day: ${before.day}');

                if (now.day != before.day) {
                  showTimeStamp = true;
                }
                // if (difference.inDays >= 1) {
                //   showTimeStamp = true;
                // }
              }
              return taskItem(taskCtrl.taskList[index], index, showTimeStamp);
            },
            childCount: taskCtrl.taskList.length
            )
          ),
        )
      ],
    ));

  }

  Widget taskItem(Task taskItem, int index, bool showTimeStamp) {
    return GestureDetector(
      onTap: () {
        // AddTaskDialog().show(context);
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          showTimeStamp ? Text(
            // '08.00 AM',
            "${DateTime.fromMillisecondsSinceEpoch(taskItem.expiresTime!).format('Y, m, d')}",
            style: const TextStyle(
              color: CustomColors.TextHeader,
              fontWeight: FontWeight.w600,
            ),
          ).marginOnly(bottom: 5.h, left: 15.w) : SizedBox(),
          Slidable(
              endActionPane: ActionPane(
                motion: const ScrollMotion(),
                extentRatio: 0.4,
                children: [
                  InkWell(
                    onTap: () {
                      // debugPrint('删除');
                      taskCtrl.deleteTask(taskItem);
                    },
                    child: Container(
                      // key: UniqueKey(),
                      padding: const EdgeInsets.only(bottom: 10),
                      child: Container(
                        height: 35,
                        width: 35,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            color: CustomColors.TrashRedBackground),
                        // child: Image.asset('assets/images/trash.png'),
                        child: const Center(
                          child: FaIcon(FontAwesomeIcons.trashCan, size: 20, color: Colors.red),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 10.w),
                  // InkWell(
                  //   onTap: () {
                  //     // debugPrint('删除');
                  //     // taskCtrl.deleteTask(taskItem);
                  //   },
                  //   child: Container(
                  //     // key: UniqueKey(),
                  //     padding: const EdgeInsets.only(bottom: 10),
                  //     child: Container(
                  //       height: 35,
                  //       width: 35,
                  //       decoration: BoxDecoration(
                  //           borderRadius: BorderRadius.circular(50),
                  //           color: CustomColors.GreenAccent.withOpacity(0.6)),
                  //       // child: Image.asset('assets/images/trash.png'),
                  //       child: const Center(
                  //         child: FaIcon(FontAwesomeIcons.penToSquare, size: 20, color: Colors.green),
                  //       ),
                  //     ),
                  //   ),
                  // )
                ],
              ),
              child: Container(
                margin: const EdgeInsets.fromLTRB(20, 0, 20, 15),
                padding: const EdgeInsets.fromLTRB(10, 13, 10, 13),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    stops: const [0.015, 0.015],
                    colors: [ Color(taskTypeCtrl.getTaskByType(taskItem.type ?? 0)), Colors.white],
                  ),
                  borderRadius: const BorderRadius.all(
                    Radius.circular(5.0),
                  ),
                  boxShadow: const [
                    BoxShadow(
                      color: CustomColors.GreyBorder,
                      blurRadius: 10.0,
                      spreadRadius: 5.0,
                      offset: Offset(0.0, 0.0),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        taskItem.isDone = taskItem.isDone == 1 ? 0 : 1;
                        taskCtrl.updateTask(taskItem);
                      },
                      child: Image.asset(taskItem.isDone == 1
                          ? 'assets/images/checked.png' : 'assets/images/checked-empty.png', width: 15, height: 22),
                    ),
                    const SizedBox(width: 5),
                    Text(
                      // '08.00 AM',
                      "${DateTime.fromMillisecondsSinceEpoch(taskItem.expiresTime!).format('A, H:i')}",
                      style: const TextStyle(color: CustomColors.TextGrey),
                    ),
                    const SizedBox(width: 5),
                    Expanded(
                        child: Text(
                          taskCtrl.taskList[index].title ?? '',
                          style: taskItem.isDone == 1 ? const TextStyle(
                            color: CustomColors.TextGrey,
                            decoration: TextDecoration.lineThrough,
                            decorationColor: CustomColors.TextGrey,
                          ) : const TextStyle(
                            color: CustomColors.TextHeader,
                            fontWeight: FontWeight.w600,
                          ),
                        )
                    ),
                    GestureDetector(
                      onTap: () {
                        taskItem.remind = taskItem.remind == 1 ? 0 : 1;
                        taskCtrl.updateTask(taskItem);
                      },
                      child: FaIcon(FontAwesomeIcons.solidBell, size: 17, color:
                      taskItem.remind == 1 ? CustomColors.BellYellow : Colors.grey),
                    )
                  ],
                ),
              )
          )
        ],
      ),
    );
  }

  Widget noTodo() {
    return Column(
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // appBar(),
        const SizedBox(height: 10),
        Hero(
          tag: 'Clipboard',
          child: Image.asset(
            'assets/images/Clipboard-empty.png',
            width: 120,
            height: 120,
          ),
        ),
        const SizedBox(height: 10),
        Column(
          children: <Widget>[
            Text(
              'No tasks',
              style: TextStyle(
                  fontSize: 22,
                  fontWeight: FontWeight.w500,
                  color: CustomColors.TextHeader),
            ),
            SizedBox(height: 15),
            Text(
              'You have no tasks to do.',
              style: TextStyle(
                  fontSize: 17,
                  fontWeight: FontWeight.w400,
                  color: CustomColors.TextBody,
                  fontFamily: 'opensans'),
              textAlign: TextAlign.center,
            ),
          ],
        ),
        const SizedBox(height: 50),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
